<?php
include_once "inc/crm.inc.php";

if(!isset($_POST['username'])){
	echo rendertpl("login.tpl", array("captchaid"=>mt_rand(10, 10000)));
	myexit();
}

else{
	include_once ROOT_DIR.'/bc/block.user.php';
	
	//用户名密码安全性验证
	$username = $_POST['username'];
	$passwd = $_POST['passwd'];
	if(isempty($username)){
		echo rendertpl("login.tpl", array("error"=>"请提供用户名"));
		myexit();
	}
	else{
		if(preg_match('/[\'\"\(\)]+/', $username)){
			echo rendertpl("login.tpl", array("error"=>"请不要尝试使用非法字符"));
			myexit();
		}
	}
	
	//验证验证码:
	$captchaerror = true;
	if(!isempty(@$_POST['captchaid']) && !isempty(@$_POST['captcha'])){
		$ret = verifycaptcha($_POST['captchaid'], $_POST['captcha']);
		if(0===$ret){
			$captchaerror = false;
		}
	}
	if($captchaerror){
		echo rendertpl("login.tpl", array("error"=>"验证码不正确"));
			myexit();
	}
	
	if($cf_adminlogin==$_POST['username']){
		if($cf_adminpasswd==$_POST['passwd'])
			$user = array("id"=>$cf_adminid, "login"=>$cf_adminlogin, "name"=>$cf_adminname);
		else
			$user = null;
	}
	else{
		$params = array("login"=>$_POST['username'], "passwd"=>md5($_POST['passwd']));
		$user = getuser($params);
		error_log(print_r($user, 1));
		error_log("post".print_r($_POST, 1));
		$user = @$user[0];
	}
	if($user){
		$_SESSION['userid'] = $user['id'];
		$_SESSION['username'] = $user['name'];
		$_SESSION['login'] = $user['login'];
		
		header("Location: ".SERVER_ROOT."{$cf_entry}?view=order");
		myexit();
	}
	else{
		echo rendertpl("login.tpl", array("error"=>"用户名或密码错误"));
		myexit();
	}
	
}
?>